import {
	defineStore
} from 'pinia';
import {
	ref
} from "vue"

import {
	getUser
} from '@/pages_nbst/api/auth.js'


export const useUserStore = defineStore('user', () => {
	const id = ref(0)
	const phone = ref('')
	const username = ref('')
	const from = ref('')
	const avatarUrl = ref('')
	const studentNum = ref('')
	const subjectId = ref(0)
	const gradeId = ref(0)
	const role = ref(0)
	const subject = ref('')
	const classes = ref('')
	const test = ref('')
	const setUser = (user) => {
		console.log('setUser');
		return new Promise((resolve, reject) => {
			if (user) {
				if (user.phone) {
					phone.value = user.phone
				}
				if (user?.nick_name || user.username) {
					username.value = user?.nick_name || user.username
				}
				if (user.from) {
					from.value = user.from
				}
				if (user?.avatar_url || user.avatarUrl) {
					avatarUrl.value = user?.avatar_url || user.avatarUrl
				}
				if (user.test) {
					test.value = user.test
				}
				resolve('setUser !')
			} else {
				getUser().then(res => {
					id.value = res.id
					phone.value = res.phone
					username.value = res.username
					from.value = res.from
					studentNum.value = res.student_num
					avatarUrl.value = res.avatar_url
					subjectId.value = res.subject_id
					gradeId.value = res.grade_id
					role.value = res.role
					subject.value = res.subject
					classes.value = res.classes
					resolve(res)
				}).catch(e => {
					reject(e)
				})
			}
		})
	}
	return {
		setUser,
		id,
		username,
		phone,
		from,
		avatarUrl,
		studentNum,
		subjectId,
		role,
		classes,
		subject,
		test,
	}
})